package com.lfs.market.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lfs.market.constants.OrderConstant;
import com.lfs.market.constants.ProductConstant;
import com.lfs.market.exception.ServiceException;
import com.lfs.market.mapper.OrdersMapper;
import com.lfs.market.model.dto.OrderDto;
import com.lfs.market.model.entity.Orders;
import com.lfs.market.model.entity.PaymentPay;
import com.lfs.market.model.entity.User;
import com.lfs.market.model.enums.ResultCode;
import com.lfs.market.model.vo.AdminOrderDetailVo;
import com.lfs.market.model.vo.PaymentOrderVo;
import com.lfs.market.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 * 业务处理
 **/
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {

    @Autowired
    private OrdersService ordersService;

    @Autowired
    private ProductInfoService productInfoService;

    @Autowired
    private PaymentPayService paymentPayService;

    @Autowired
    private UserService userService;

    @Autowired
    private UserAddressService addressService;

    /**
     * 根据订单号查询订单信息
     *
     * @param orderNo
     * @return
     */
    @Override
    public Orders selectByOrderNo(String orderNo) {
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Orders::getOrderNo, orderNo);
        return baseMapper.selectOne(queryWrapper);
    }

    /**
     * 创建订单
     *
     * @param ordersDto
     */
    @Transactional
    @Override
    public String createOrder(OrderDto ordersDto) {
        //当前买入商品用户
        String userId = StpUtil.getLoginIdAsString();
        System.out.println(userId);

        Orders orders = new Orders();
        orders.setOrderNo(UUID.randomUUID().toString().replace("-", ""));
        orders.setStatus(OrderConstant.NO_PAID);
        orders.setCreateTime(new Date());
        orders.setUserId(userId);
        //商品所属用户
        orders.setProductUserId(ordersDto.getProductUserId());
        orders.setProductId(ordersDto.getProductId());
        orders.setProductName(ordersDto.getProductName());
        orders.setTotalPrice(ordersDto.getProductPrice());
        orders.setAddress(ordersDto.getAddress());

//        UserAddress address = addressService.lambdaQuery().eq(UserAddress::getUserId, userId).one();


        boolean save = ordersService.save(orders);
        if (!save) {
            throw new ServiceException(ResultCode.SaveError);
        }
        return orders.getOrderNo();
    }


    /**
     * 根据订单返回信息包含价格和订单号
     *
     * @param OrderNo
     * @return
     */
    @Override
    public PaymentOrderVo selectOrderNo(String OrderNo) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getOrderNo, OrderNo);

        Orders orders = baseMapper.selectOne(wrapper);
        PaymentOrderVo paymentOrderVo = new PaymentOrderVo();
        paymentOrderVo.setOrderNo(OrderNo);
        paymentOrderVo.setProductPrice(orders.getTotalPrice());

        return paymentOrderVo;
    }

    /**
     * 根据订单完成支付
     *
     * @param orderNo
     */
    @Override
    public void finishPay(String orderNo) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getOrderNo, orderNo);
        Orders orders = baseMapper.selectOne(wrapper);

        //完成订单
        orders.setStatus(OrderConstant.HAVE_PAID);
        baseMapper.updateById(orders);
        String productId = orders.getProductId();

        //商品卖出
        productInfoService.productSoldOut(productId);

        PaymentPay paymentPay = new PaymentPay();
        paymentPay.setPaymentPrice(orders.getTotalPrice());
        paymentPay.setOrderId(orderNo);
        paymentPay.setTimeCreate(new Date());
        paymentPay.setUserId(orders.getUserId());
        paymentPay.setPaymentStatus(ProductConstant.PUBLISH);

        paymentPayService.createPaymentPay(paymentPay);
    }

    /**
     * 根据用户的id获取订单的id
     *
     * @param userId
     */
    @Override
    public List<Orders> getByUserId(String userId) {
        List<Orders> orderList = ordersService.lambdaQuery().
                eq(Orders::getUserId, userId)
                .eq(Orders::getStatus, OrderConstant.HAVE_PAID)
                .list();
        return orderList;
    }

    /**
     * 根据订单id查询订单信息
     *
     * @param id
     * @return
     */
    @Override
    public AdminOrderDetailVo getOrderDetail(String id) {
        AdminOrderDetailVo detailVo = new AdminOrderDetailVo();
        Orders orders = ordersService.getById(id);
        detailVo.setOrderNo(orders.getOrderNo());
        detailVo.setStatus(orders.getStatus());
        detailVo.setCreateTime(orders.getCreateTime());
        detailVo.setProductName(orders.getProductName());
        detailVo.setPrice(orders.getTotalPrice());
        detailVo.setAddress(orders.getAddress());
        User user = userService.getByUserId(orders.getUserId());

        detailVo.setPhone(user.getPhone());
        detailVo.setUserName(user.getNickName());
        return detailVo;
    }

    /**
     * 定时清除订单
     *
     * @return
     */
    @Override
    public List<Orders> orderTaskDelete() {
        List<Orders> ordersList = baseMapper.orderTaskDelete();
        return ordersList;
    }

//    /**
//     * 查询订单详情
//     *
//     * @param productOrderId
//     * @return
//     */
//    @Override
//    public OrderDetailVo selectOrderDetail(String productOrderId) {
//        OrderDetailVo detailVo = new OrderDetailVo();
//        Orders orders = ordersService.lambdaQuery().eq(Orders::getOrderNo, productOrderId).one();
//        detailVo.setAddress(orders.getAddress());
//        detailVo.setOrderNo(orders.getOrderNo());
//        ProductInfo productInfo = productInfoService.lambdaQuery().eq(ProductInfo::getId, orders.getProductId()).one();
//        detailVo.setProductName(productInfo.getTitle());
//        detailVo.setProductPrice(orders.getTotalPrice());
//        return detailVo;
//    }
}